<?php
/**
 * @package DomBase
 * @author Oliver Leisalu
 */
class DomBrowser {
	
	/**
	 * @var String [unknown, ie, mozilla, opera, safari]
	 */
	private static $browser = 'unknown';

	/**
	 * @var String [unknown, windows, mac, linux, os2, beos]
	 */
	private static $platform = 'unknown';
	
	public function resolve() {
		self::resolveBrowser();
		self::resolvePlatform();
	}
	
	private static function resolveBrowser() {
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') ) {
			//$browser = 'Safari';
			self::$browser = 'safari';

		} else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') ) {
				
			if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') )  {
				//$browser = 'Netscape (Gecko/Netscape)';
				self::$browser = 'netscape';
					
			} else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') ) {
				//$browser = 'Mozilla Firefox (Gecko/Firefox)';
				self::$browser = 'mozilla';
					
			} else {
				//$browser = 'Mozilla (Gecko/Mozilla)';
				self::$browser = 'mozilla';
			}

		} else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ) {
			//$browser = 'Internet Explorer (MSIE/Compatible)';
				
			self::$browser = 'ie';
		} else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === true) {
			//$browser = 'Opera';
			self::$browser = 'opera';
		}
	}

	private static function resolvePlatform() {

		if ( stripos("win", $_SERVER['HTTP_USER_AGENT']))
			self::$platform = "windows";
		elseif (stripos("mac", $_SERVER['HTTP_USER_AGENT']))
			self::$platform = "mac";
		elseif (stripos("linux", $_SERVER['HTTP_USER_AGENT']))
			self::$platform = "linux";
		elseif (stripos("OS/2", $_SERVER['HTTP_USER_AGENT']))
			self::$platform = "os2";
		elseif (stripos("BeOS", $_SERVER['HTTP_USER_AGENT']))
			self::$platform = "beos";
	}
	
	// -----------------------------------------
	// Platform testing methods
	// -----------------------------------------
	
	public static function isOsWindows() {
		return self::$platform == 'windows';
	}
	
	public static function isOsMac() {
		return self::$platform == 'mac';
	}
	
	public static function isOsLinux() {
		return self::$platform == 'linux';
	}
	
	public static function isOsOs2() {
		return self::$platform == 'os2';
	}
	
	public static function isOsBeos() {
		return self::$platform == 'beos';
	}
	
	public static function isOsUnknown() {
		return self::$platform == 'unknown';
	}
	
	// -----------------------------------------
	// Browser testing methods
	// -----------------------------------------
	
	public static function isIE() {
		return self::$browser == 'ie';
	}

	public static function isMozilla() {
		return self::$browser == 'mozilla';
	}

	public static function isOpera() {
		return self::$browser == 'opera';
	}

	public static function isSafari() {
		return self::$browser == 'safari';
	}

	public static function isUnknown() {
		return self::$browser == 'unknown';
	}

	
	// -----------------------------------------
	// Search engine bot testing methods
	// -----------------------------------------
	
	/**
	 * Returns list of IP addresses used by search engines. Cached daily.
	 *
	 * @return String
	 */
	public static function getSearchEngineIpAddresses() {
		
		if( !defined('DOM_BOTS_CACHE_FILE') )	throw new RuntimeException('Constant DOM_BOTS_CACHE_FILE is undefined!');	
		if( !defined('DOM_BOTS_CACHE_GEN_FILE') )	throw new RuntimeException('Constant DOM_BOTS_CACHE_GEN_FILE is undefined!');
		
		
		// ---------------------------------------------
		// decide if needed to recreate cache
		// ---------------------------------------------
		
		$cacheFileExists = file_exists(DOM_BOTS_CACHE_FILE);
		$createCache = false;
		if( !$cacheFileExists ) {
			$createCache = true;
		} else {
			$fileModTime = filemtime(DOM_BOTS_CACHE_FILE);
			
			// allow cache creating only on night hours (3:00 to 7:00)!
			if( date("Ymd", $fileModTime ) != date("Ymd") && in_array( (int)date('H',$fileModTime), array(3,4,5,6,7) ) ) {
				$createCache = true;
			}
		}
		
		// if cache is already being created by someone then don't start creating new cache. Use old list instead.
		if( $createCache === true && is_file(DOM_BOTS_CACHE_GEN_FILE) ) {
	    	$createCache = false;	
	    }	
		
	    
	    // ---------------------------------------------
	    // create cache
	    // ---------------------------------------------
	    if ( $createCache === true ) {
	    	
	    	file_put_contents( DOM_BOTS_CACHE_GEN_FILE, '1');
	    	
			$lists = array(
				'http://labs.getyacg.com/spiders/google.txt',
				'http://labs.getyacg.com/spiders/inktomi.txt',
				'http://labs.getyacg.com/spiders/lycos.txt',
				'http://labs.getyacg.com/spiders/msn.txt',
				'http://labs.getyacg.com/spiders/altavista.txt',
				'http://labs.getyacg.com/spiders/askjeeves.txt',
				'http://labs.getyacg.com/spiders/wisenut.txt',
			);
		    
			$listOfIps = '';
			foreach($lists as $list) {
				$ch = curl_init( $list );
			
				curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); 
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				
				$listOfIps .= curl_exec($ch)."\n\r";
				curl_close($ch);
			}
		   
			file_put_contents( DOM_BOTS_CACHE_FILE, $listOfIps );
			unlink(DOM_BOTS_CACHE_GEN_FILE);
			
	    } else {
	    	if( $cacheFileExists === true)
	    		$listOfIps = file_get_contents( DOM_BOTS_CACHE_FILE );
	    	else
	    		$listOfIps = '';
	    }
	    // ---------------------------------------------
	    
		return $listOfIps;
	}
	
	/**
	 * Tells if current client is search engine bot or not.
	 * @return Bool
	 */
	public static function isSearchEngineBot() {
		$bots = array(
			"Teoma", "alexa", "froogle", "Gigabot", "inktomi",
			"looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
			"Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
			"crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
			"msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
			"Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
			"Mediapartners-Google", "Sogou web spider", "WebAlta Crawler"
		);
		
		foreach( $bots as $bot ) {
			if( stristr($_SERVER['HTTP_USER_AGENT'], $bot) )
				return true;
		}
		return false;
	}
	
	/**
	 * Tells if current client is search engine bot or not. 
	 * Use DomBrowser::isSearchEngineBot as its faster, but might not be so accurate.
	 * @return Bool
	 */
	public static function isSearchEngineBotIp() {
		return (bool)stristr(self::getSearchEngineIpAddresses(), $_SERVER['REMOTE_ADDR']);
	}

}
DomBrowser::resolve();
?>